package com.yinhai.service.impl;

import com.yinhai.domain.LoginUser;
import com.yinhai.domain.ResponseResult;
import com.yinhai.domain.User;
import com.yinhai.service.LoginService;
import com.yinhai.utils.JwtUtil;
import com.yinhai.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : chengxd
 * @create 2024/2/14 0:05
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;


    @Override
    public ResponseResult login(User user) {
//        使用AuthenticationManager进行用户认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if(Objects.isNull(authenticate)){
            // 当不存在的时候，抛出异常
            throw new RuntimeException("登陆失败");
        }
        // 通过凭证获取到登录对象
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        // 通过登录对象获取到userId
        String userId = loginUser.getUser().getId().toString();

        String jwt = JwtUtil.createJWT(userId);


        // 成功的时候，使用userId生成一个jwt，将用户信息进行存储
        Map<String,String> maps = new HashMap<>();

        maps.put("token",jwt);

        redisCache.setCacheObject("login："+userId,loginUser);
        
        return new ResponseResult(200,"登录成功",maps);
    }

    @Override
    public ResponseResult logout() {
        // 从SecurityContextHolder取出存在其中的验证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        redisCache.deleteObject("login："+userId);

        return new ResponseResult(200,"退出成功");
    }
}
